import axios from 'axios'

class HttpRequest {
  constructor (baseUrl) {
    this.baseUrl = baseUrl;
    this.queue = {}
  }
  getInsideConfig () {
    return {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {

    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      this.queue[url] = true;
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url);
      const { data, status } = res;

      if(status===200){
        switch (data.code){
          case 200:
            return Promise.resolve(data.data);
          case 400:
            return  Promise.reject(res.data.msg);
          default:
            return Promise.reject(data.msg|| '服务器异常')
        }
      }
    }, (err) => {
      this.destroy(url);
      const status = err.response&&err.response.status;
      return Promise.reject('Network error')
    })

  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
